//导入js
var network = require('network.js')
var util = require('util.js')
var md5 = require('md5.js')
var config = require('../config')

//获取应用实例
var app = getApp()

function payWeChat(requestHandler,callback) {
    request(requestHandler,callback);
}
function request(requestHandler,callback) {
    unifiedorder(requestHandler.out_trade_no,requestHandler.total_fee,requestHandler.body,requestHandler.product_id,callback);
}

// 随机字符串产生函数
function createNonceStr () {
    return Math.random().toString(36).substr(2, 15)
}
// 时间戳产生函数
function createTimeStamp() {
    return parseInt(new Date().getTime() / 1000) + ''
}
function unifiedorder (out_trade_no, total_fee,body,product_id,callback) {

    var total_fee_str = 100*total_fee;
    //var total_fee_str = 1;

    var appid = app.globalData.appid;
    var mch_id =  app.globalData.mch_id;
    var openid = app.globalData.userInfo.openid;
    var notify_url = "http://localhost/notify"
    var nonceStr = createNonceStr();
    var  spbill_create_ip='61.50.221.43';
    var stringA = "appid=" + appid + "&body=" + body + "&mch_id="
        + mch_id + "&nonce_str=" + nonceStr + "&notify_url=" + notify_url
        +  "&openid=" + openid + "&out_trade_no=" + out_trade_no
        +  "&sign_type=MD5&spbill_create_ip=" + spbill_create_ip
        + "&total_fee=" + total_fee_str +  "&trade_type=" + 'JSAPI';

    var stringSignTemp = stringA + "&key=e229652cfc8c8b91af944cdca5c59f65"; //注：key为商户平台设置的密钥key
    var sign =md5.md5(stringSignTemp).toUpperCase();
    //var sign=hash_hmac("sha256",stringSignTemp,'e229652cfc8c8b91af944cdca5c59f65').toUpperCase()

    //调用该接口在微信支付服务后台生成预支付交易单，返回正确的预支付交易后调起支付
    var url = "https://api.mch.weixin.qq.com/pay/unifiedorder"
    var formData = "<xml>"
    formData += "<appid>" + appid + "</appid>" //appid
    formData += "<body>" + body + "</body>"
    formData += "<mch_id>" + mch_id + "</mch_id>" //商户号
    formData += "<nonce_str>" + nonceStr + "</nonce_str>" //随机字符串，不长于32位。
    formData += "<notify_url>" + notify_url + "</notify_url>"
    formData += "<openid>" + openid + "</openid>"
    formData += "<out_trade_no>" + out_trade_no + "</out_trade_no>"
    formData += "<sign_type>MD5</sign_type>"
    formData += "<spbill_create_ip>61.50.221.43</spbill_create_ip>"
    formData += "<total_fee>" + total_fee_str + "</total_fee>"
    formData += "<trade_type>JSAPI</trade_type>"
    formData += "<sign>" + sign + "</sign>"
    formData += "</xml>"
    wx.request({
            url:url,
            method: 'POST',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            data: formData,
            success: (res) => {

    if (res && res.statusCode === 200){
        var result_code = getXMLNodeValue('result_code', res.data.toString("utf-8"));
        var resultCode = result_code.split('[')[2].split(']')[0];
        if(resultCode ==='SUCCESS'){ //成功
            var prepay_id = getXMLNodeValue('prepay_id', res.data.toString("utf-8")).split('[')[2].split(']')[0]; //获取到prepay_id
            payOrder(appid,nonceStr,'prepay_id='+prepay_id,total_fee_str,out_trade_no,callback);
            //签名
            saveOrder(nonceStr,prepay_id,out_trade_no);
        }else{
            var err_code_des = getXMLNodeValue('err_code_des',res.data.toString("utf-8"));
            var errDes = err_code_des.split('[')[2].split(']')[0];
        }

    }
}
});
}

//解析xml
function getXMLNodeValue (node_name, xml) {
    var tmp = xml.split("<" + node_name + ">");
    var _tmp = tmp[1].split("</" + node_name + ">");
    return _tmp[0];
}
function payOrder (appid,nonceStr,prepay_id,total_fee_str,out_trade_no,callback) {
    var timeStamp = createTimeStamp();
    var stringSignTemp = 'appId='+appid
        +'&nonceStr='+nonceStr
        +'&package='+prepay_id
        +'&signType=MD5'
        +'&timeStamp='+timeStamp
        +'&key=e229652cfc8c8b91af944cdca5c59f65';
    var paySign =md5.md5(stringSignTemp);

    wx.requestPayment(
        {
            'appId':appid,
            'nonceStr': nonceStr,
            'package': prepay_id,
            'signType': 'MD5',
            'timeStamp': timeStamp,
            'paySign': paySign,
            'success':function(res){
                console.log('requestPayment---'+res);
                savePayRecord(total_fee_str,out_trade_no,callback);
                typeof callback == "function" && callback('success')
            },
            'fail':function(res){
                if (res.errMsg=='requestPayment:fail cancel'){
                    typeof callback == "function" && callback('cancel')
                }
            },
            'complete':function(res){
            }
        })
}
function saveOrder (nonceStr, prepay_id,out_trade_no) {
    var formData={
        nonceStr:nonceStr,
        prepay_id:prepay_id,
        ordernum:out_trade_no,
        userid:app.globalData.userInfo.userid
    };
    console.log('saveOrder='+config.service.orderPay+'-'+nonceStr+'-'+prepay_id+'-'+out_trade_no)
    wx.request({
            url:config.service.orderPay,
            method: 'POST',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            data: formData,
            success: (res) => {
    }});
}
function savePayRecord (total_fee_str,out_trade_no,callback) {

    var formData={
        total_fee:(total_fee_str/100),
        ordernum:out_trade_no,
        userid:app.globalData.userInfo.userid,
        zt:2,
    };

    wx.request({
            url:config.service.orderUpdate,
            method: 'POST',
            header: { 'content-type': 'application/x-www-form-urlencoded' },
            data: formData,
            success: (res) => {

    }});
}
module.exports = {
    payWeChat: payWeChat,
    payOrder: payOrder

}